<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/jexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/jexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/jexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/jexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/jexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/jexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/jexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Android,Android底层," />










<meta name="description" content="其实对于初学者来说Handler的使用很容易会很容易上手，但是对于其中的机制的理解，却不会那么简单，甚至1，2年经验的android开发也可能对其内部实现原理不是很了解。">
<meta name="keywords" content="Android,Android底层">
<meta property="og:type" content="article">
<meta property="og:title" content="Android消息处理">
<meta property="og:url" content="http://ja_project.gitee.io/jexo/2018/04/18/Android消息处理/index.html">
<meta property="og:site_name" content="Ling Hu Blog">
<meta property="og:description" content="其实对于初学者来说Handler的使用很容易会很容易上手，但是对于其中的机制的理解，却不会那么简单，甚至1，2年经验的android开发也可能对其内部实现原理不是很了解。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4241874-f45514852554836e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-04-18T13:36:44.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android消息处理">
<meta name="twitter:description" content="其实对于初学者来说Handler的使用很容易会很容易上手，但是对于其中的机制的理解，却不会那么简单，甚至1，2年经验的android开发也可能对其内部实现原理不是很了解。">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/4241874-f45514852554836e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/jexo/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://ja_project.gitee.io/jexo/2018/04/18/Android消息处理/"/>





  <title>Android消息处理 | Ling Hu Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?abc8796c232e2b898d516245257842b4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/jexo/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ling Hu Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/jexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/jexo/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/jexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/jexo/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/jexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://ja_project.gitee.io/jexo/jexo/2018/04/18/Android消息处理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ling Hu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/jexo/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ling Hu Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android消息处理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-18T21:36:17+08:00">
                2018-04-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/jexo/categories/Android底层/" itemprop="url" rel="index">
                    <span itemprop="name">Android底层</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/jexo/2018/04/18/Android消息处理/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/jexo/2018/04/18/Android消息处理/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>其实对于初学者来说Handler的使用很容易会很容易上手，但是对于其中的机制的理解，却不会那么简单，甚至1，2年经验的android开发也可能对其内部实现原理不是很了解。</p>
<a id="more"></a>
<p>其中我经过的认知的过程</p>
<ol>
<li><p>初识Handler,认为没必要,直接执行方法不就好了么,为什么还要post出去,然后再在handleMessage中作处理，多此一举。</p>
</li>
<li><p>异步可使用Handler，在主线程更新ui</p>
</li>
<li><p>主线程中有个Looper不断循环，从MessageQueue中获取到Message，而Handler只是往MessageQueue中塞入Message</p>
</li>
<li><p>非主线程中也可以创建自己的Looper来处理消息，不过要自己调用Looper.prepare(),Looper.loop()，初始化和开始轮询。</p>
</li>
<li><p>MessageQueue调用了jni层的方法来实现消息处理机制</p>
</li>
</ol>
<p>笔者对整个android的消息处理机制的认知过程如上，经过的时间也很长，不是一蹴而就的。</p>
<p>今天就通过对其底层源码分析，和大家分享其内部实现原理，主要是第5步的认知，涉及到了jni层。这里主要介绍主线程中的Looper。</p>
<pre><code>注意：android源码2.3.1
</code></pre><p>我们从头开始<br>frameworks/base/core/java/android/app/ActivityThread<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">     Looper.prepareMainLooper();</span><br><span class="line">        <span class="keyword">if</span> (sMainThreadHandler == <span class="keyword">null</span>) &#123;</span><br><span class="line">            sMainThreadHandler = <span class="keyword">new</span> Handler();</span><br><span class="line">        &#125;</span><br><span class="line">      ...</span><br><span class="line">      ...</span><br><span class="line">        Looper.loop();</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们这里以ActivityThread为入口来分析消息处理机制，每个app启动的时候，都会创建自己的ActivityThread，并且在main方法中也会创建主线程中的Looper。</p>
<p>这里如果对app整个启动流程不是特别清楚的话，建议先看下<br><a href="http://www.jianshu.com/p/9da5bb46835c" target="_blank" rel="noopener">http://www.jianshu.com/p/9da5bb46835c</a></p>
<p>frameworks/base/core/java/android/os/Looper<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="title">Looper</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        mQueue = <span class="keyword">new</span> MessageQueue();</span><br><span class="line">        mRun = <span class="keyword">true</span>;</span><br><span class="line">        mThread = Thread.currentThread();</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">prepare</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">        sThreadLocal.set(<span class="keyword">new</span> Looper());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">prepareMainLooper</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        prepare();</span><br><span class="line">        setMainLooper(myLooper());</span><br><span class="line">       ...</span><br><span class="line">    &#125;</span><br><span class="line">  ...</span><br><span class="line">  ...</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Looper <span class="title">myLooper</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (Looper)sThreadLocal.get();</span><br><span class="line">    &#125;</span><br><span class="line">  ...</span><br></pre></td></tr></table></figure></p>
<p>首先我们要理解<code>ThreadLocal</code>这个类的作用<br><a href="http://www.cnblogs.com/alphablox/archive/2013/01/20/2869061.html" target="_blank" rel="noopener">http://www.cnblogs.com/alphablox/archive/2013/01/20/2869061.html</a></p>
<p>简单来说，就是为了实现每个线程中有对应一个Looper。</p>
<p>上面代码主要做了</p>
<ol>
<li>创建Looper,MessageQueue</li>
<li>把Looper与当前主线程关联</li>
</ol>
<p>mQueue其实就是MessageQueue，在Looper的构造方法中创建。<br>下面分析下MessageQueue。</p>
<p>frameworks/base/core/java/android/os/MessageQueue<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">native</span> <span class="keyword">void</span> <span class="title">nativeInit</span><span class="params">()</span></span>;</span><br><span class="line">...</span><br><span class="line">MessageQueue() &#123;</span><br><span class="line">        nativeInit();</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>创建MessageQueue,其实主要调用了native方法。</p>
<p>其实在我们分析android源码的时候，要找到的对应的native方法，其实是一件很麻烦的事情，因为我们只知道方法名，并不知道对应的.c文件或者.cpp文件是哪个，这样就造成了我们阅读的障碍，这里有个比较笨的方法就是使用<code>grep &#39;**&#39; -R .</code>来查询文件内容。但是毕竟android源码比较庞大，这样做其实还是很麻烦的，我这里暂时也没有更好的办法，主要还是参考了别人的文章，找到了对应的文件。</p>
<p>frameworks/base/core/jni/android_os_MessageQueue<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">NativeMessageQueue::NativeMessageQueue() &#123;</span><br><span class="line">    mLooper = Looper::getForThread();</span><br><span class="line">    <span class="keyword">if</span> (mLooper == <span class="literal">NULL</span>) &#123;</span><br><span class="line">        mLooper = <span class="keyword">new</span> Looper(<span class="literal">false</span>);</span><br><span class="line">        Looper::setForThread(mLooper);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">android_os_MessageQueue_setNativeMessageQueue</span><span class="params">(JNIEnv* env, jobject messageQueueObj,</span></span></span><br><span class="line"><span class="function"><span class="params">        NativeMessageQueue* nativeMessageQueue)</span> </span>&#123;</span><br><span class="line">    env-&gt;SetIntField(messageQueueObj, gMessageQueueClassInfo.mPtr,</span><br><span class="line">             <span class="keyword">reinterpret_cast</span>&lt;jint&gt;(nativeMessageQueue));</span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">android_os_MessageQueue_nativeInit</span><span class="params">(JNIEnv* env, jobject obj)</span> </span>&#123;</span><br><span class="line">    NativeMessageQueue* nativeMessageQueue = <span class="keyword">new</span> NativeMessageQueue();</span><br><span class="line">  ...</span><br><span class="line">    android_os_MessageQueue_setNativeMessageQueue(env, obj, nativeMessageQueue);</span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line"><span class="keyword">static</span> JNINativeMethod gMessageQueueMethods[] = &#123;</span><br><span class="line">    &#123; <span class="string">"nativeInit"</span>, <span class="string">"()V"</span>, (<span class="keyword">void</span>*)android_os_MessageQueue_nativeInit &#125;,</span><br><span class="line">    ...</span><br><span class="line">&#125;;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>简单地介绍下上面代码</p>
<ol>
<li>注册对应的jni方法，如nativeInit.</li>
<li>java层调用nativeInit后创建,NativeMessageQueue</li>
<li>NativeMessageQueue中创建了Looper，如java层也是跟线程绑定，但是这个jni层的Looper，跟java层的 Looper没有关系。</li>
<li>利用JNIEnv方法给java 层中的MessageQueue对象的mPtr变量设置为NativeMessageQueue的地址。</li>
</ol>
<p>下面是对jni层Looper的解析<br>frameworks/base/libs/utils/Looper<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Looper::Looper(<span class="keyword">bool</span> allowNonCallbacks) :</span><br><span class="line">        mAllowNonCallbacks(allowNonCallbacks),</span><br><span class="line">        mResponseIndex(<span class="number">0</span>) &#123;</span><br><span class="line">      ...</span><br><span class="line">      <span class="keyword">int</span> result = pipe(wakeFds);</span><br><span class="line">      ...</span><br><span class="line">      mWakeReadPipeFd = wakeFds[<span class="number">0</span>];</span><br><span class="line">      mWakeWritePipeFd = wakeFds[<span class="number">1</span>];</span><br><span class="line">      ...</span><br><span class="line">      mEpollFd = epoll_create(EPOLL_SIZE_HINT);</span><br><span class="line">      ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>其实Looper的代码很多，这里我就贴出了关键的几行，但是涉及到的知识点却很多。</p>
<ol>
<li>pipe，创建读写管道<br> <a href="http://www.cnblogs.com/kunhu/p/3608109.html" target="_blank" rel="noopener">http://www.cnblogs.com/kunhu/p/3608109.html</a></li>
<li>epoll_create，管理io<br> <a href="http://www.cnblogs.com/Anker/archive/2013/08/17/3263780.html" target="_blank" rel="noopener">http://www.cnblogs.com/Anker/archive/2013/08/17/3263780.html</a></li>
</ol>
<p>其实我对这2者也并不是很熟悉。但是我知道以下几点，我认为就足够了。</p>
<ol>
<li>pipe创建读写2个通道</li>
<li>epoll监听io</li>
<li>epoll_wait会io阻塞，等到pipe管道中写入内容后，阻塞结束。</li>
</ol>
<p>以上其实都是ActivityThread中调用Looper.prepareMainLooper之后的流程。主要是进行一些初始化，创建一些基础的对象。</p>
<p>下面我们来分析Looper.loop()，消息轮询。</p>
<p>frameworks/base/core/java/android/os/Looper<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">loop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Looper me = myLooper();</span><br><span class="line">        MessageQueue queue = me.mQueue;</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            Message msg = queue.next(); <span class="comment">// might block</span></span><br><span class="line">             ...</span><br><span class="line">                msg.target.dispatchMessage(msg);</span><br><span class="line">             ...</span><br><span class="line">                msg.recycle();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>这段代码就是开启while死循环，不断从MessageQueue中获取Message,一看最重要的肯定是queue.next()获取Message这个方法。<br>继续跟入。<br>frameworks/base/core/java/android/os/MessageQueue<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">final</span> Message <span class="title">next</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">     <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">          ...</span><br><span class="line">          nativePollOnce(mPtr, nextPollTimeoutMillis);</span><br><span class="line">          ...</span><br><span class="line">      &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>next方法去获取Message，最终还是调用nativePollOnce方法，传入的2个参数，这里介绍下。</p>
<ol>
<li><p>mPtr，是MessageQueue的一个变量，在前面其实已经介绍过了，其实是指向jni层的NativeMessageQueue的地址。</p>
</li>
<li><p>nextPollTimeoutMillis其实是epoll_wait时，如果pipe中没有内容写入的等待时间，举个例子，如果nextPollTimeoutMillis为1000，那么这1秒中如果pipe中一直没有东西写入，那么，epoll_wait那么会阻塞1秒，然后继续运行，如果为0的话，epoll_wait就不会阻塞，如果为-1的话，如果pipe中没有东西写入，就会一直阻塞。</p>
</li>
</ol>
<p>下面我们来看下nativePollOnce的具体实现。</p>
<p>frameworks/base/core/jni/android_os_MessageQueue<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="keyword">void</span> NativeMessageQueue::pollOnce(<span class="keyword">int</span> timeoutMillis) &#123;</span><br><span class="line">    mLooper-&gt;pollOnce(timeoutMillis);</span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">android_os_MessageQueue_nativePollOnce</span><span class="params">(JNIEnv* env, jobject obj,</span></span></span><br><span class="line"><span class="function"><span class="params">        jint ptr, jint timeoutMillis)</span> </span>&#123;</span><br><span class="line">    NativeMessageQueue* nativeMessageQueue = <span class="keyword">reinterpret_cast</span>&lt;NativeMessageQueue*&gt;(ptr);</span><br><span class="line">    nativeMessageQueue-&gt;pollOnce(timeoutMillis);</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>其实在前面那一步就已经介绍了，ptr是NativeMessageQueue指针，在方法中强转为NativeMessageQueue对象后，调用他的pollOnce，<br>然后再调用NativeMessageQueue中的Looper的pollOnce方法</p>
<p>frameworks/base/libs/utils/Looper<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="keyword">int</span> Looper::pollOnce(<span class="keyword">int</span> timeoutMillis, <span class="keyword">int</span>* outFd, <span class="keyword">int</span>* outEvents, <span class="keyword">void</span>** outData) &#123;</span><br><span class="line"><span class="keyword">int</span> result = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">        <span class="keyword">while</span> (mResponseIndex &lt; mResponses.size()) &#123;</span><br><span class="line">         ...</span><br><span class="line">        result = pollInner(timeoutMillis);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> Looper::pollInner(<span class="keyword">int</span> timeoutMillis) &#123;</span><br><span class="line">    ...</span><br><span class="line">    ...</span><br><span class="line">     <span class="keyword">int</span> eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);</span><br><span class="line">    ...</span><br><span class="line">     <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; eventCount; i++) &#123;</span><br><span class="line">        <span class="keyword">int</span> fd = eventItems[i].data.fd;</span><br><span class="line">        <span class="keyword">uint32_t</span> epollEvents = eventItems[i].events;</span><br><span class="line">        <span class="keyword">if</span> (fd == mWakeReadPipeFd) &#123;</span><br><span class="line">            <span class="keyword">if</span> (epollEvents &amp; EPOLLIN) &#123;</span><br><span class="line">                awoken();</span><br><span class="line">            &#125;</span><br><span class="line">            ...</span><br><span class="line">         &#125;</span><br><span class="line">        ...</span><br><span class="line">      &#125;</span><br><span class="line">      ..</span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line"><span class="keyword">void</span> Looper::awoken() &#123;</span><br><span class="line">...</span><br><span class="line">    <span class="keyword">do</span> &#123;</span><br><span class="line">        nRead = read(mWakeReadPipeFd, buffer, <span class="keyword">sizeof</span>(buffer));</span><br><span class="line">    &#125; <span class="keyword">while</span> ((nRead == <span class="number">-1</span> &amp;&amp; errno == EINTR) || nRead == <span class="keyword">sizeof</span>(buffer));</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<ol>
<li>epoll_wait阻塞，等待<code>timeoutMillis</code>毫秒或者pipe中有输入</li>
<li>如果有消息过来了，其实会先往pipe中输入，解除epoll_wait阻塞</li>
<li>for循环eventCount，判断是否是当前线程的管道的fd，如果是，就调用awoken方法，read一下把东西读出来</li>
</ol>
<p>其实到这里了，已经把大部分重要的代码贴出，下面我们来过一遍，走下整个流程，来梳理一下。</p>
<ol>
<li>Looper初始化，这里就不过多介绍了。</li>
<li>调用loop，不断从MessageQueue取数据。<br>第一次调用时，<code>nextPollTimeoutMillis=0</code>，epoll_wait没有造成阻塞，马上运行到下面，由于刚开始，还没有消息过来<code>eventCount=0</code>,所以<br>java层中。<br>frameworks/base/core/java/android/os/MessageQueue<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">final</span> Message <span class="title">next</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">    ...</span><br><span class="line">    nativePollOnce(mPtr, nextPollTimeoutMillis);</span><br><span class="line">            <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">                ...</span><br><span class="line">                <span class="keyword">final</span> Message msg = mMessages;</span><br><span class="line">                <span class="keyword">if</span> (msg != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">final</span> <span class="keyword">long</span> when = msg.when;</span><br><span class="line">                    <span class="keyword">if</span> (now &gt;= when) &#123;</span><br><span class="line">                        mBlocked = <span class="keyword">false</span>;</span><br><span class="line">                        mMessages = msg.next;</span><br><span class="line">                        msg.next = <span class="keyword">null</span>;</span><br><span class="line">                        <span class="keyword">if</span> (Config.LOGV) Log.v(<span class="string">"MessageQueue"</span>, <span class="string">"Returning message: "</span> + msg);</span><br><span class="line">                        <span class="keyword">return</span> msg;</span><br><span class="line">          <span class="keyword">else</span>&#123;</span><br><span class="line">                    nextPollTimeoutMillis = -<span class="number">1</span>;</span><br><span class="line">          &#125;</span><br><span class="line">    ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>调用<code>nativePollOnce</code>其实主要作用就是在jni层中epoll_wait等待pipe管道有新的输入，即有新的 Message。</p>
<p>刚刚开始，没有阻塞，所以<code>nativePollOnce</code>马上返回。</p>
<p><code>Message</code>其实是一个链表结构。</p>
<p>mMessages变量始终指向第一个Message.</p>
<p>由于刚开始还没有Message,所有mMessages = null</p>
<p>进入else，设置nextPollTimeoutMillis = -1;<br>由于还处于for之中，所以继续调用native方法<code>nativePollOnce</code>,<br>前面我已经介绍了，当nextPollTimeoutMillis=-1时，其实在epoll_wait会一直阻塞。</p>
<p>这时，我又不得不提到这篇优秀的文章<br><a href="http://www.jianshu.com/p/9da5bb46835c" target="_blank" rel="noopener">http://www.jianshu.com/p/9da5bb46835c</a></p>
<p>这里我并不清楚第一个Message消息是哪里传过来的，但是在App启动时Activity的生命周期中大部分都是利用handleMessage来处理的，姑且当作是第一个Message吧。</p>
<p>我们都知道是通过Handler来发送Message,由于Handler中发送 Message方法很多，但是最后都是调用<code>sendMessageAtTime</code></p>
<p>frameworks/base/core/java/android/os/Handler<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">sendMessageAtTime</span><span class="params">(Message msg, <span class="keyword">long</span> uptimeMillis)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">boolean</span> sent = <span class="keyword">false</span>;</span><br><span class="line">        MessageQueue queue = mQueue;</span><br><span class="line">        <span class="keyword">if</span> (queue != <span class="keyword">null</span>) &#123;</span><br><span class="line">            msg.target = <span class="keyword">this</span>;</span><br><span class="line">            sent = queue.enqueueMessage(msg, uptimeMillis);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            RuntimeException e = <span class="keyword">new</span> RuntimeException(</span><br><span class="line">                <span class="keyword">this</span> + <span class="string">" sendMessageAtTime() called with no mQueue"</span>);</span><br><span class="line">            Log.w(<span class="string">"Looper"</span>, e.getMessage(), e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sent;</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>这里的mQueue其实就是我们在Looper中创建的MessageQueue.<br>frameworks/base/core/java/android/os/MessageQueue<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">enqueueMessage</span><span class="params">(Message msg, <span class="keyword">long</span> when)</span> </span>&#123;</span><br><span class="line">       ...</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">boolean</span> needWake;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">          ...</span><br><span class="line">            Message p = mMessages;</span><br><span class="line">            <span class="keyword">if</span> (p == <span class="keyword">null</span> || when == <span class="number">0</span> || when &lt; p.when) &#123;</span><br><span class="line">                msg.next = p;</span><br><span class="line">                mMessages = msg;</span><br><span class="line">                needWake = mBlocked; <span class="comment">// new head, might need to wake up</span></span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                Message prev = <span class="keyword">null</span>;</span><br><span class="line">                <span class="keyword">while</span> (p != <span class="keyword">null</span> &amp;&amp; p.when &lt;= when) &#123;</span><br><span class="line">                    prev = p;</span><br><span class="line">                    p = p.next;</span><br><span class="line">                &#125;</span><br><span class="line">                msg.next = prev.next;</span><br><span class="line">                prev.next = msg;</span><br><span class="line">                needWake = <span class="keyword">false</span>; <span class="comment">// still waiting on head, no need to wake up</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (needWake) &#123;</span><br><span class="line">            nativeWake(mPtr);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>enqueueMessage其实这个方法很重要，它对Message先进行了排序，要早运行的排在了前面，比较晚运行的排在队列后面。</p>
<p>前面介绍了mMessages其实是指向Message链表的第一个Message.<br>这时候来了个新的Message，由于是刚刚开始mMessage = null;<br>所以进入了if()中的语句。</p>
<p>这里有个变量需要特别解释，<code>needWake</code>,顾名思义，是否需要唤醒。<br>就整篇文章而言，其实阻塞的就一个地方，就是epoll_wait，所以needWake指的需不需要唤醒，也就是指的这里。<br>mBlocked代表，当前的epoll_wait是否正在阻塞，如果是阻塞的，<br>mBlocked = true,所以needWake = mBlocked = true,也就是需要唤醒。<br>如果非阻塞那么，needWake = false.<br>最终是<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if (needWake) &#123;</span><br><span class="line">            nativeWake(mPtr);</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure></p>
<p>前面已经介绍了，由于nextPollTimeoutMillis=-1，epoll_wait正在阻塞，所以needWake = true;所以这个时候需要唤醒。</p>
<p>这里我就 不介绍跳转过程了，最终调用jni层的Looper中的wake方法</p>
<p>frameworks/base/libs/utils/Looper<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="keyword">void</span> Looper::wake() &#123;</span><br><span class="line">...</span><br><span class="line">    <span class="keyword">do</span> &#123;</span><br><span class="line">        nWrite = write(mWakeWritePipeFd, <span class="string">"W"</span>, <span class="number">1</span>);</span><br><span class="line">    &#125; <span class="keyword">while</span> (nWrite == <span class="number">-1</span> &amp;&amp; errno == EINTR);</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>前面其实我已经介绍过了epoll_wait有2种方式不再阻塞</p>
<ol>
<li>等待传入的timeout参数时间到</li>
<li>pipe管道中有新的输入</li>
</ol>
<p>由于这个时候的timeout=-1代表一直阻塞，所以只能通过往pipe管道中写入东西，才能不阻塞epoll_wait.如上write一个内容。其实写的内容是什么并不重要，如上，其实就是写了一个<code>W</code>字符。</p>
<p>这个时候，epoll_wait不再阻塞，继续往下运行。<br>frameworks/base/libs/utils/Looper<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="keyword">int</span> Looper::pollInner(<span class="keyword">int</span> timeoutMillis) &#123;</span><br><span class="line">    ...</span><br><span class="line">     <span class="keyword">int</span> eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);</span><br><span class="line">    ...</span><br><span class="line">     <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; eventCount; i++) &#123;</span><br><span class="line">        <span class="keyword">int</span> fd = eventItems[i].data.fd;</span><br><span class="line">        uint32_t epollEvents = eventItems[i].events;</span><br><span class="line">        <span class="keyword">if</span> (fd == mWakeReadPipeFd) &#123;</span><br><span class="line">            <span class="keyword">if</span> (epollEvents &amp; EPOLLIN) &#123;</span><br><span class="line">                awoken();</span><br><span class="line">            &#125;</span><br><span class="line">          ...</span><br><span class="line">        &#125;</span><br><span class="line">    ...</span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line"><span class="keyword">void</span> Looper::awoken() &#123;</span><br><span class="line">    ...</span><br><span class="line">     <span class="keyword">do</span> &#123;</span><br><span class="line">        nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));</span><br><span class="line">    &#125; <span class="keyword">while</span> ((nRead == -<span class="number">1</span> &amp;&amp; errno == EINTR) || nRead == sizeof(buffer));</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>这个时候进入awoken方法，把写入内容读出。没有造成阻塞。</p>
<p>也就是java层中的MessageQueue中的next方法中的<code>nativePollOnce</code>没有造成阻塞，继续运行。</p>
<p>frameworks/base/core/java/android/os/MessageQueue<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">final</span> Message <span class="title">next</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      ...</span><br><span class="line"></span><br><span class="line">      <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">          ...</span><br><span class="line">          nativePollOnce(mPtr, nextPollTimeoutMillis);</span><br><span class="line">          ...</span><br><span class="line">           <span class="keyword">final</span> Message msg = mMessages;</span><br><span class="line">              <span class="keyword">if</span> (msg != <span class="keyword">null</span>) &#123;</span><br><span class="line">                  <span class="keyword">final</span> <span class="keyword">long</span> when = msg.when;</span><br><span class="line">                  <span class="keyword">if</span> (now &gt;= when) &#123;</span><br><span class="line">                      mBlocked = <span class="keyword">false</span>;</span><br><span class="line">                      mMessages = msg.next;</span><br><span class="line">                      msg.next = <span class="keyword">null</span>;</span><br><span class="line">                      <span class="keyword">if</span> (Config.LOGV) Log.v(<span class="string">"MessageQueue"</span>, <span class="string">"Returning message: "</span> + msg);</span><br><span class="line">                      <span class="keyword">return</span> msg;</span><br><span class="line">                  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                      nextPollTimeoutMillis = (<span class="keyword">int</span>) Math.min(when - now, Integer.MAX_VALUE);</span><br><span class="line">                  &#125;</span><br><span class="line">              &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                  nextPollTimeoutMillis = -<span class="number">1</span>;</span><br><span class="line">              &#125;</span><br><span class="line">          ...</span><br><span class="line">    &#125;</span><br><span class="line">      ...</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>这时<code>nativePollOnce</code>阻塞结束，继续运行，if (now &gt;= when) 是为了判断这个消息是否延迟，对应我们Handler中延迟发送的一些方法，如postDelay()等。这里直接认为没有延时。</p>
<p>在Message链表中把第一个Message移除返回。<br>最后调用Handler的handleMessage，这不是重点我就直接略过了。</p>
<p>等到Message都处理完了之后，获取到Message 为null。nextPollTimeoutMillis又被置为-1,然后又在epoll_wait中进行阻塞。</p>
<p>这里对延时发送Message的没有详细讲解，主要还是2点。</p>
<ol>
<li>在添加Message的时候进行时间排序了，把Message插入到对应的位置。</li>
<li>主要还是利用nextPollTimeoutMillis，在epoll_wait的时候阻塞，等待。</li>
</ol>
<p>这里我就不再详细赘述了。</p>
<p>####问题</p>
<p>在分析源码的时候，我遇到了一个问题，整个消息机制，其实就是一个死循环，一直在执行，当没有消息的时候epoll_wait阻塞。<br>为什么epoll_wait在主线程阻塞不会造成卡顿，或者ANR?</p>
<p><img src="http://upload-images.jianshu.io/upload_images/4241874-f45514852554836e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="29125917-E9AB-4187-AA9C-A685980FE347.png"></p>
<p>我这里就不再过多赘述了。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>Donate comment here</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/jexo/images/wechatpay.png" alt="Ling Hu 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/jexo/images/alipay.png" alt="Ling Hu 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/jexo/tags/Android/" rel="tag"># Android</a>
          
            <a href="/jexo/tags/Android底层/" rel="tag"># Android底层</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/jexo/2018/04/18/Android有背景颜色下使用水波纹效果/" rel="next" title="Android有背景颜色下使用水波纹效果">
                <i class="fa fa-chevron-left"></i> Android有背景颜色下使用水波纹效果
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/jexo/2018/04/18/如何使android模块debug和release随着主模块变化/" rel="prev" title="如何使android模块debug和release随着主模块变化">
                如何使android模块debug和release随着主模块变化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/jexo/images/avatar.jpg"
                alt="Ling Hu" />
            
              <p class="site-author-name" itemprop="name">Ling Hu</p>
              <p class="site-description motion-element" itemprop="description">Android,源码解析,每天进步一点点</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/jexo/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/jexo/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/jexo/tags/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/javalong" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ling Hu</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/jexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/jexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/jexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/jexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/jexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/jexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    
      <style>
        a.gitment-editor-footer-tip { display: none; }
        .gitment-container.gitment-footer-container { display: none; }
      </style>
    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: getId(),
            owner: 'javalong',
            repo: 'RxJava-Operator',
            
            lang: "zh-Hans" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: '06b042e57b8420f5002a6407348dde078bcde761',
            
                client_id: '1b5481d6512b2f28d7a2'
            }});
        gitment.render('gitment-container');
      }

      function getId(){
            if( window.location.pathname.length>=50){
                return window.location.pathname.substr(0,50)
            }else{
                return window.location.pathname
            }
      }

      
      renderGitment();
      
      </script>
    







  





  

  

  

  
  

  

  

  

</body>
</html>
